<?php

namespace app\business\controller;

use app\models\{Shoplist, Cate, Goods, GoodsSpec, Order, OrderGoods, User, Region, Withdrawal, ShopLog};
use think\Db;
use think\Validate;
use EasyWeChat\Factory;


class Shop extends Base
{

    public function shop_withdrawal()
    {
        $model = new Withdrawal();
        $shopmodel = new Shoplist();
        $data = $this->request->get();
        $result = $model->order('id desc');
        if (!empty($data['status'])) {
            $result = $result->where('status', $data['status']);
        }
        $result = $result->where('atype', 1)->where('shopid', $this->request->bussiness['id']);
        if (!empty($data['title'])) {
            $result = $result->where('name|cards', 'like', '%' . $data['title'] . '%');
        }
        $result = $result->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['shopname'] = $shopmodel->where('id', $results['shopid'])->value('title');
        }
        $shoplist = $shopmodel->field('id,title,account')->select();
        return view(null, [
            'list' => $result
        ]);
    }


    public function shop_withdrawaledit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'money' => 'require|gt:0|float',
                'name' => 'require',
                'cards' => 'require',
                'type' => 'require|in:1,2,3',
                'bank' => 'require',
                'password' => 'require'
            ], [
                'money.require' => '金额不能为空',
                'money.gt' => '用户金额必须大于0',
                'money.float' => '用户金额必须为数字',
                'name.require' => '用户姓名不能为空',
                'cards.require' => '用户卡号|账号不能为空',
                'type.require' => '提现类型不能为空',
                'type.in' => '提现类型不正确',
                'bank.require' => '所属银行|公司不能为空',
                'password.require' => '密码不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $model = new Shoplist();
            $shoplogmodel = new ShopLog();
            $withmodel = new Withdrawal();
            $shop = $model->where('id', $this->request->bussiness['id'])->find();
            if ($shop['money'] < abs($data['money'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '可提现余额不足']);
            }
            if ($shop['password'] != md5(md5($data['password']))) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码不正确']);
            }
            Db::startTrans();
            try {
                //返回商户余额
                $withmodel->save([
                    'atype' => 1,
                    'shopid' => $this->request->bussiness['id'],
                    'money' => $data['money'],
                    'name' =>  $data['name'],
                    'cards' =>  $data['cards'],
                    'bank' =>  $data['bank'],
                    'type' =>  $data['type'],
                    'status' => 1,
                ]);
                $shoplogmodel->MoneyEdit($shop, -abs($data['money']), 2, '申请提现,商家ID:' . $this->request->bussiness['id']);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $model = new Shoplist();
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            return view(null, [
                'row' => $results
            ]);
        }
    }

    public function qrcode()
    {
        $name = 'business' . $this->request->bussiness['id'] . '.png';
        $qcode = url('/wechat/' . $name, '', '', true);
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/wechat/";
        if (!file_exists($path . $name)) {
            $config = config('wechat.');
            $app = Factory::miniProgram($config);
            $rm = $app->app_code->getUnlimit('shopid=' . $this->request->bussiness['id'], [
                'page'  => '',
                'width' => 600,
            ]);
            if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $rm->save($path, $name);
            }
        }
        return json(['code' => 0, 'data' => $qcode]);
    }

    public function shoplist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'ranges' => 'require',
                'startsend' => 'require',
                'lat' => 'require',
                'lon' => 'require',
                'status' => 'require'
            ], [
                'ranges.require' => '商家配送范围不能为空',
                'startsend.require' => '商家配送起送价不能为空',
                'lat.require' => '商家地址不能为空',
                'lon.require' => '商家地址不能为空',
                'status.require' => '商家状态不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            $resdata = [
                'location' => $data['lat'] . ',' . $data['lon'],
                'key' => '2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT'
            ];
            try {
                $result = api_curl($url, $resdata);
                $result = json_decode($result, true);
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            $data['street'] = 0;
            if (!empty($result) && $result['status'] == 0) {
                if (!empty($result['result']['address_reference']['town']['id'])) {
                    $street = (new Region())
                        ->where(['level' => 4, 'code' => $result['result']['address_reference']['town']['id']])
                        ->find();
                } else {
                    $street = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $result['result']['ad_info']['adcode'])
                        ->where('name|remark', 'like', '%' . $result['result']['address_reference']['town']['title'] . '%')->find();
                }
                $data['street'] = $street['code'] ?? 0;
            }
            if (empty($data['street'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '街道不存在，']);
            }
            $area = (new Region())->where(['level' => 3, 'id' => $street['parent_id']])->find();
            if (empty($area)) {
                return json(['code' => 1, 'data' => [], 'msg' => '区域不存在']);
            }
            $city = (new Region())->where(['level' => 2, 'id' => $area['parent_id']])->find();
            if (empty($city)) {
                return json(['code' => 1, 'data' => [], 'msg' => '城市不存在']);
            }
            $province = (new Region())->where(['level' => 1, 'id' => $city['parent_id']])->find();
            if (empty($province)) {
                return json(['code' => 1, 'data' => [], 'msg' => '省份不存在']);
            }
            $data['area'] = $area['area_code'] ?? 0;
            $data['city'] = $city['area_code'] ?? 0;
            $data['province'] = $province['area_code'] ?? 0;
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Shoplist();
            $shop = $model->where('id', $data['id'])->find();
            if (empty($shop)) {
                return json(['code' => 1, 'data' => [], 'msg' => '商户不存在']);
            }
            if ($shop['street'] != $data['street']) {
                return json(['code' => 1, 'data' => [], 'msg' => '街道发生变更，请联系管理员']);
            }
            $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Shoplist();
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            return view(null, [
                'row' => $results
            ]);
        }
    }

    public function xpgoodslist()
    {
        $model = new Goods();
        $shopmodel = new Shoplist();
        $data = $this->request->get();
        $results = $model->where('isdel', 1)->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('title|goodsSn', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['cate'])) {
            $results = $results->where('cate', $data['cate']);
        }
        $results = $results->where('shopid', 1)->where('shopid', '<>', $this->request->bussiness['id']);
        $result = $results->select();
        $shoplist = $shopmodel->field('id,title,account')->select();
        foreach ($result as $results) {
            $results['images'] = json_decode($results['images'], true) ?? [];
            $results['shopname'] = $shopmodel->where('id', $results['shopid'])->value('title');
            $results['goodspec'] = (new GoodsSpec())->where('goodid', $results['id'])->where('isdel', 1)->field('name,price,oprice')->select();
            $results['catename'] = (new Cate())->where('id', $results['cate'])->value('name');
            $xpid = $model->where(['shopid' => $this->request->bussiness['id'], 'xpid' => $results['id']])->find();
            $results['ishave'] = !empty($xpid) ? 1 : 2;
        }
        $cate = (new Cate())->where('shopid', 1)->where('ishow', 1)->select();
        $mycate = (new Cate())->where('shopid', $this->request->bussiness['id'])->where('ishow', 1)->select();
        return view(null, [
            'shoplist' => $shoplist,
            'list' => $result,
            'mycate' => $mycate,
            'cate' => $cate
        ]);
    }

    public function xpgoodslist_edit()
    {
        $data = $this->request->post();
        //查询分类是否存在
        if (empty($data['cate'])) {
            return json(['code' => 1, 'data' => [], 'msg' => '请选择导入的分类']);
        }
        if (empty($data['id']) || count($data['id']) <= 0) {
            return json(['code' => 1, 'data' => [], 'msg' => '请选择商品']);
        }
        if ($this->request->bussiness['id'] == 1) {
            return json(['code' => 1, 'data' => [], 'msg' => '当前商户不可导入商品']);
        }
        $mycate = (new Cate())->where('id', $data['cate'])->where('shopid', $this->request->bussiness['id'])->where('ishow', 1)->find();
        if (empty($mycate)) {
            return json(['code' => 1, 'data' => [], 'msg' => '分类信息不存在']);
        }
        $goodsmodel = new Goods();
        //查询所有商品
        $goodslist = $goodsmodel->where(['id' => $data['id']])->where('shopid', 1)->select();
        foreach ($goodslist as $goods) {
            $goods = $goods->toArray();
            $xpid = $goodsmodel->where(['shopid' => $this->request->bussiness['id'], 'xpid' => $goods['id']])->find();
            $goodsspec = (new GoodsSpec())->where('goodid', $goods['id'])->where('isdel', 1)->select();
            if (empty($xpid) && count($goodsspec) > 0) {
                $goodsspec = $goodsspec->toArray();
                $goods['xpid'] = $goods['id'];
                unset($goods['id']);
                $goods['shopid'] = $this->request->bussiness['id'];
                $goods['cate'] = $data['cate'];
                Db::startTrans();
                try {
                    $goodsid = $goodsmodel->insertGetId($goods);
                    foreach ($goodsspec as $spec) {
                        unset($spec['id']);
                        $spec['shopid'] = $goods['shopid'];
                        $spec['goodid'] = $goodsid;
                        $spec['goodsstock'] = 999;
                        $spec['warnStock'] = 10;
                        (new GoodsSpec())->insert($spec);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '部分导入失败']);
                }
            }
        }
        return json(['code' => 0, 'data' => [], 'msg' => '导入完成']);
    }

    public function goodslist()
    {
        $model = new Goods();
        $shopmodel = new Shoplist();
        $data = $this->request->get();
        $results = $model->where('isdel', 1)->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('title|goodsSn', 'like', '%' . $data['title'] . '%');
        }
        $results = $results->where('shopid', $this->request->bussiness['id']);
        $result = $results->paginate(10, false, ['query' => $this->request->param()]);
        $shoplist = $shopmodel->field('id,title,account')->select();
        foreach ($result as $results) {
            $results['images'] = json_decode($results['images'], true) ?? [];
            $results['shopname'] = $shopmodel->where('id', $results['shopid'])->value('title');
            $results['catename'] = (new Cate())->where('id', $results['cate'])->value('name');
        }
        return view(null, [
            'shoplist' => $shoplist,
            'list' => $result
        ]);
    }

    public function goodslist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'goodsSn' => 'require',
                'cate' => 'require',
                'descs' => 'require',
                'isSale' => 'require|in:1,2',
                'isBest' => 'require|in:1,2',
                'isHot' => 'require|in:1,2',
                'isNew' => 'require|in:1,2',
                'goodsDesc' => 'require'
            ], [
                'title.require' => '商品名称不能为空',
                'goodsSn.require' => '商品编号不能为空',
                'cate.require' => '商品分类不能为空',
                'descs.require' => '商品描述不能为空',
                'isSale.require' => '上架类型不能为空',
                'isSale.in' => '上架类型不正确',
                'isBest.require' => '推荐类型不能为空',
                'isBest.in' => '推荐类型不正确',
                'isHot.require' => '热卖类型不能为空',
                'isHot.in' => '热卖类型不正确',
                'isNew.require' => '新品类型不能为空',
                'isNew.in' => '新品类型不正确',
                'goodsDesc.require' => '商品描述不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $data['shopid'] = $this->request->bussiness['id'];
            if (!empty($data['images'])) {
                $data['images'] = json_encode($data['images'], true);
            }
            if (!empty($data['parpam'])) {
                $data['parpam'] = json_encode($data['parpam'], true);
            }
            if (empty($data['spec']) || count($data['spec']) <= 0) {
                return json(['code' => 1, 'data' => [], 'msg' => '规格信息不能少于一个']);
            }
            if (isset($data['file'])) {
                unset($data['file']);
            }
            $shopmodel = new Shoplist();
            $goodmodel = new Goods();
            $catemodel = new Cate();
            $specmodel = new GoodsSpec();

            //查找商家是否存
            $shoplist = $shopmodel->where('id', $data['shopid'])->find();
            if (!$shoplist) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家不存在']);
            }
            //查找分类是否存在
            $cate = $catemodel->where(['shopid' =>  $data['shopid'], 'id' => $data['cate']])->find();
            if (!$cate) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家分类不存在']);
            }
            //商品编号唯一
            $good = $goodmodel->where(['goodsSn' => $data['goodsSn'], 'shopid' => $data['shopid'], 'isdel' => 1])->find();
            if ((!empty($good) && empty($data['id']))) {
                return json(['code' => 1, 'data' => [], 'msg' => '商品编号已被使用']);
            }
            if (!empty($good) && !empty($data['id']) && $data['id'] != $good['id']) {
                return json(['code' => 1, 'data' => [], 'msg' => '商品编号已被使用']);
            }
            $insert = $data;
            unset($insert['spec']);
            if (empty($data['id'])) {
                Db::startTrans();
                try {
                    $data['id'] = $goodmodel->insertGetid($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['shopid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            } else {
                Db::startTrans();
                try {
                    $goodmodel->where('id', $data['id'])->update($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['shopid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            }
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $model = new Goods();
            $specmodel = new GoodsSpec();
            $shopmodel = new Shoplist();
            $catemodel = new Cate();
            $cate = [];
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            $shoplist = $shopmodel->field('id,title,account')->select();
            $cate = $catemodel->where('shopid', $this->request->bussiness['id'])->select();
            if ($results) {
                $results['images'] = json_decode($results['images'], true) ?? [];
                $results['parpam'] = json_decode($results['parpam'], true) ?? [];
                $results['speclist'] = $specmodel->order('is_default desc')->where(['shopid' => $results['shopid'], 'isdel' => 1, 'goodid' => $results['id']])->select();
            }
            return view(null, [
                'row' => $results,
                'shoplist' => $shoplist,
                'cate' => $cate
            ]);
        }
    }

    public function goodslist_del()
    {
        $id = trim(input('id'), ',');
        $model = new Goods();
        $res = $model->where(['id' => $id, 'shopid' => $this->request->bussiness['id']])->update(['isdel' => 2]);
        if ($res) {
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
    }

    public function goodsspec_del()
    {
        $id = trim(input('id'), ',');
        $model = new GoodsSpec();
        $goodsspec = $model->where(['id' => $id, 'isdel' => 1, 'shopid' => $this->request->bussiness['id']])->find();
        if (empty($goodsspec)) {
            return json(['code' => 1, 'data' => [], 'msg' => '库存规格不存在']);
        }
        //查询规格商品是否超过1个
        $havespec = $model->where(['goodid' => $goodsspec['goodid'], 'isdel' => 1])->count();
        if ($havespec <= 1) {
            return json(['code' => 1, 'data' => [], 'msg' => '库存规格必须保留一个']);
        }
        $res = $model->where(['id' => $id, 'shopid' => $this->request->bussiness['id']])->update(['isdel' => 2]);
        if ($res) {
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
    }

    public function order()
    {
        $model = new Order();
        $shopmodel = new Shoplist();
        $usermodel = new User();
        $regionmodel = new Region();
        $data = $this->request->get();
        $result = $model->order('id desc');
        if (!empty($data['ispay'])) {
            $result = $result->where('ispay', $data['ispay']);
        }
        if (!empty($data['user_id'])) {
            $result = $result->where('user_id', $data['user_id']);
        }
        if (!empty($data['payment'])) {
            $result = $result->where('payment', $data['payment']);
        }
        if (!empty($data['rece'])) {
            $result = $result->where('rece', $data['rece']);
        }
        if (!empty($data['status'])) {
            $result = $result->where('status', $data['status']);
        }
        $result = $result->where('shopid', $this->request->bussiness['id']);
        if (!empty($data['ordersn'])) {
            $result = $result->where('ordersn', 'like', '%' . $data['ordersn'] . '%');
        }
        if (!empty($data['createtime1'])) {
            $result = $result->whereTime('created', '>=', $data['createtime1']);
        }
        if (!empty($data['createtime2'])) {
            $result = $result->whereTime('created', '<', $data['createtime2']);
        }
        if (!empty($data['finishtime1'])) {
            $result = $result->whereTime('fintime', '>=', $data['finishtime1']);
        }
        if (!empty($data['finishtime2'])) {
            $result = $result->whereTime('fintime', '<', $data['finishtime2']);
        }
        if (!empty($data['atype'])) {
            switch ($data['atype']) {
                case '1':
                    $result = $result->where(['type' => 1, 'status' => [3, 4]]);
                    break;
                case '2':
                    $result = $result->where(['type' => 2, 'status' => [3, 4]]);
                    break;
                default:
                    # code...
                    break;
            }
        }
        $sumtotal = $result->sum('total');
        $result = $result->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['user'] = $usermodel->where('id', $results['user_id'])->field('id,nickName,gender,avatarUrl,mobile')->find();
            $results['shop'] = $shopmodel->where('id', $results['shopid'])->field('id,title')->find();
            $results['province_name'] = $regionmodel->where(['area_code' => $results['province'], 'level' => 1])->value('name');
            $results['city_name'] = $regionmodel->where(['area_code' => $results['city'], 'level' => 2])->value('name');
            $results['area_name'] = $regionmodel->where(['area_code' => $results['area'], 'level' => 3])->value('name');
            if ($results['payment'] == 1) {
                $results['payment_text'] = '货到支付';
            } else {
                $results['payment_text'] = '微信支付';
            }
            if ($results['rece'] == 1) {
                $results['rece_text'] = '正常';
            } else {
                $results['rece_text'] = '待售后';
            }
            switch ($results['status']) {
                case '1':
                    $results['status_text'] = '待付款';
                    break;
                case '2':
                    $results['status_text'] = '待配送';
                    break;
                case '3':
                    $results['status_text'] = '待收货';
                    break;
                case '4':
                    $results['status_text'] = '已完成';
                    break;
                case '5':
                    $results['status_text'] = '已取消';
                    break;
                default:
                    break;
            }
        }
        $shoplist = $shopmodel->field('id,title,account')->select();
        //查询是否可以直接发货
        $admins = Db::name('admin')->where('find_in_set(' . $this->request->bussiness['street'] . ',street)')->where(['type' => [3, 4]])->find();
        if (empty($admins)) {
            $admins = Db::name('admin')->where('find_in_set(' . $this->request->bussiness['area'] . ',area)')->where(['type' => [2]])->find();
        }
        return view(null, [
            'shoplist' => $shoplist,
            'list' => $result,
            'admins' => $admins,
            'sumtotal' => $sumtotal
        ]);
    }

    public function order_goods()
    {
        $model = new OrderGoods();
        $ordersn = $this->request->get('ordersn', 0);
        $result = $model->where('ordersn', $ordersn)->order('id desc');
        $result = $result->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['images'] = json_decode($results['images'], true) ?? [];
        }
        return view(null, [
            'list' => $result
        ]);
    }

    public function order_status()
    {
        $model = new Order();
        $id = $this->request->get('id/d', 0);
        $status = $this->request->get('status/d', 0);
        $order = $model->where(['id' => $id, 'shopid' => $this->request->bussiness['id']])->find();
        Db::startTrans();
        try {
            $model->order_status($order, $status, 1, $this->request->bussiness['id']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
    }
}
